<?php
class Upload {
	//Save name of file
	var $_fileName;
	//Save size of file
	var $_fileSize;
	//var of file extent of file upload
	var $_fileExtension;
	//Source of file
	var $_fileTmp;
	//Source on Server of file
	var $_uploadDir;
	// var of error
	var $_errors;
	//Constructor of object
	function __construct($file_name) {
		//echo __METHOD__;
		$fileInfo = $_FILES[$file_name];
		$this -> _fileName = $fileInfo['name'];
		$this -> _fileSize = $fileInfo['size'];
		$this -> _fileExtension = $this -> getFileExtension();
		$this -> _fileTmp = $fileInfo['tmp_name'];
	}

	//function get extent of file name
	function getFileExtension() {
		$subject = $this -> _fileName;
		$pattern = '#\.([^\.]+)$#i';
		preg_match($pattern, $subject, $matches);
		return $matches[1];
		echo '<pre>';
		print_r($matches);
		echo '</pre>';
	}

	//function set extent of file name can upload
	//param string (ex: gif|jpg|png)
	function setFileExtension($value) {
		$subject = $this -> _fileExtension;
		$pattern = '#(' . $value . ')#i';
		if (preg_match($pattern, $subject) != 1) {
			$this -> _errors[] = 'extension of file is error';
		}
	}

	//max size of upload file
	//param int (ex: 100kb)
	function setFileSize($value) {
		$size = $value * 1024;
		if ($this -> _fileSize > $size) {
			$this -> _errors[] = 'Size of file is limited';
		}
	}

	//Source upload to
	//param string (ex: images/)
	function setUploadDir($value) {
		if (file_exists($value)) {
			$this -> _uploadDir = $value;
		} else {
			$this -> _errors[] = 'Source file is invalid';
		}
	}

	function isVail() {
		$flagErr = false;
		if (count($this -> _errors) > 0) {
			$flagErr = true;
		}
		return $flagErr;
	}

	function getFileName() {
		return $this -> _fileName;
	}

	//function Upload
	function upload($rename = false, $prefix = 'file') {
		if ($rename == true) {
			$source = $this -> _fileTmp;
			$dect = $this -> _uploadDir . $this -> _fileName;
		} else {
			$source = $this -> _fileTmp;
			$dect = $this -> _uploadDir . $prefix . time() . '.' . $this -> _fileExtension;
		}
		copy($source, $dect);
	}
}